package com.lockmem.study;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;

import com.lockmem.Conf.ConfValue;
import com.lockmem.DB.Row;
import com.lockmem.DB.RowEnglish;
import com.lockmem.constants.MyActivity;
import com.lockmem.listener.ListenerService;

import android.os.Bundle;
import android.app.AlertDialog;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.Context;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.PagerTitleStrip;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.*;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

@SuppressWarnings("deprecation")
public class StudyActivity extends MyActivity {
	/** Called when the activity is first created. */
	/**
	 * Scan mode as True , Answer mode as False
	 */
	private boolean state = true;
	private String tag = "StudyActivity";
	private TextView viceTextView;
	private TextView mainTextView;
	private TextView dateTV;
	boolean ChEn;
	private RelativeLayout dateLayout, mainvicetvLayout;

	private ViewPager mViewPager;
	private PagerTitleStrip mPagerTitleStrip;
	private int StudyNum = 0;
	private List<Row> rows;

	private TextView timeTV, gotittv, unlocktv;
	private myPagerAdapter mPagerAdapter;
	private ArrayList<View> views;
	private ArrayList<String> titles;
	private View pageview;
	private Button btnItemUnknow;
	private Button[] btnItem = new Button[3];
	private List<ChoiceQuestion> ques;

	private int max_visited_Item = -1;
	protected float lingmindu = 250;
	private TextView rightAns;
	private TextView wrongAns;
	private String rightAnsStr = "";
	private String wrongAnsStr = "";
	private Button btnUnlock;
	private boolean repeat = false;
	public static final int FLAG_HOMEKEY_DISPATCHED = 0x80000000;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// ȥ��������

		this.getWindow().setFlags(FLAG_HOMEKEY_DISPATCHED,FLAG_HOMEKEY_DISPATCHED);
		setContentView(R.layout.activity_study);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);// ȫ����ʾ

		// this.getWindow().setBackgroundDrawableResource(R.drawable.p1);
		mViewPager = (ViewPager) findViewById(R.id.viewpager);
		dateLayout = (RelativeLayout) findViewById(R.id.date);
		// mPagerTitleStrip = (PagerTitleStrip) findViewById(R.id.pagertitle);
		repeat = this.getIntent().getBooleanExtra("repeat", false);
		Log.v("1", "on create study");
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		Log.v("1", "on resume study");

		super.onResume();
	}

	protected void onPause() {
		// mKeyguardLock.reenableKeyguard();
		Log.v("1", "on pause study");
		super.onPause();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if ((!repeat) && keyCode == KeyEvent.KEYCODE_BACK)
			return false;
		if (event.KEYCODE_SEARCH == keyCode)
			return false;
		if (keyCode == event.KEYCODE_HOME) {
			// Toast.makeText(this, "home", Toast.LENGTH_LONG).show();
		
			return false;
		}
		if (keyCode == event.KEYCODE_POWER) {
			//
			// getWindow().clearFlags(FLAG_HOMEKEY_DISPATCHED);
		}
		return super.onKeyDown(keyCode, event);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.study, menu);
		for (int i = 0; i < menu.size(); i++) {
			menu.getItem(i).setOnMenuItemClickListener(
					new OnMenuItemClickListener() {
						@Override
						public boolean onMenuItemClick(MenuItem item) {
							// TODO Auto-generated method stub
							switch (item.getItemId()) {
							case R.id.menuItem_exit_id:
								StudyActivity.this.finish();
								break;
							case R.id.menuItem_explain_id:
								new AlertDialog.Builder(StudyActivity.this)
										.setTitle("使用说明")
										.setMessage(
												"上滑:标记单词为“掌握”\r\n下滑:紧急解锁\r\n")
										.setPositiveButton("确定", null).show();
							}
							return false;
						}
					});
		}
		return true;
	}

	@Override
	protected void onStart() {
		Log.v("1", "onstart Study");
		Intent intent = new Intent(this, ListenerService.class);
		this.startService(intent);
		super.onStart();
	}

	/**
	 * @return
	 */
	private myPagerAdapter initAnsPages() {
		views = new ArrayList<View>();
		titles = new ArrayList<String>();
		final LayoutInflater mLi = getInflater();
		for (int i = 0; i < StudyNum; i++) {
			pageview = mLi.inflate(R.layout.answerview, null);
			mainTextView = (TextView) pageview.findViewById(R.id.mainTextView1);
			btnItem[0] = (Button) pageview.findViewById(R.id.itemA);
			btnItem[1] = (Button) pageview.findViewById(R.id.itemB);
			btnItem[2] = (Button) pageview.findViewById(R.id.itemC);
			btnItemUnknow = (Button) pageview.findViewById(R.id.itemUnknow);
			if (ser.getSkin() != ConfValue.Skin_Pink) {
				turnBoyTheme(pageview.findViewById(R.id.wordLayout), 3);
				turnBoyTheme(pageview.findViewById(R.id.layItemA), 3);
				turnBoyTheme(pageview.findViewById(R.id.layItemB), 3);
				turnBoyTheme(pageview.findViewById(R.id.layItemC), 3);
				turnBoyTheme(pageview.findViewById(R.id.layItemU), 3);
				turnBoyTheme(pageview.findViewById(R.id.answerview), 0);
			}
			btnItem[0].setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					buttonItemClick(0);
				}
			});
			btnItem[1].setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					buttonItemClick(1);
				}
			});
			btnItem[2].setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					buttonItemClick(2);
				}
			});
			btnItemUnknow.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					buttonItemClick(3);
				}
			});

			mainTextView.setText(ques.get(i).mainText);
			for (int i1 = 0; i1 < 3; i1++) {
				btnItem[i1].setText(ques.get(i).getItems(i1));
			}
			views.add(pageview);
			titles.add("");
		}
		Log.v(tag, "this is my end");
		pageview = mLi.inflate(R.layout.resultview, null);
		rightAns = (TextView) pageview.findViewById(R.id.rightAnsText);
		wrongAns = (TextView) pageview.findViewById(R.id.wrongAnsText);

		if (ser.getSkin() != ConfValue.Skin_Pink) {
			turnBoyTheme(pageview.findViewById(R.id.rightAns), 1);
			turnBoyTheme(pageview.findViewById(R.id.wrongAns), 2);
			turnBoyTheme(pageview.findViewById(R.id.unlocklay), 3);
		}

		btnUnlock = (Button) pageview.findViewById(R.id.buttonunlock);
		if (repeat)
			btnUnlock.setText("点击返回");
		btnUnlock.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				StudyActivity.this.finish();
			}
		});
		views.add(pageview);
		titles.add("");
		return mPagerAdapter = new myPagerAdapter(views, titles);
	}

	// 初始化浏览模式下的各页面
	private myPagerAdapter initPages() {
		views = new ArrayList<View>();
		titles = new ArrayList<String>();
		LayoutInflater mLi = getInflater();
		for (int i = 0; i < rows.size(); i++) {
			pageview = mLi.inflate(R.layout.pageview, null);
			setPageViewSkinInScan();
			if (ChEn) {
				viceTextView = (TextView) pageview
						.findViewById(R.id.viceTextView);
				viceTextView.setText(((RowEnglish) (rows.get(i))).chinese);
			} else {
				mainTextView = (TextView) pageview
						.findViewById(R.id.mainTextView);
				mainTextView.setText(((RowEnglish) (rows.get(i))).english);
			}
			views.add(pageview);
			titles.add("");
		}
		pageview = mLi.inflate(R.layout.pageview, null);
		mainTextView = (TextView) pageview.findViewById(R.id.mainTextView);
		mainTextView.setText("解锁成功");
		views.add(pageview);
		titles.add("");

		setPageViewSkinInScan();
		return mPagerAdapter = new myPagerAdapter(views, titles);
	}

	private void setPageViewSkinInScan() {
		if (ser.getSkin() != ConfValue.Skin_Pink) {
			turnBoyTheme(pageview.findViewById(R.id.main), 2);
			turnBoyTheme(pageview.findViewById(R.id.pageviewbkglay), 2);
			turnBoyTheme(pageview.findViewById(R.id.remainRelativeLayout), 1);
		}// //
	}

	/**
	 * 上下和左右互斥移动的锁
	 */
	private boolean MoveLock;

	private void initViewPager() {
		ChEn = ser.getChEn();
		StudyNum = ser.getCount();
		timeTV = (TextView) findViewById(R.id.timeTextView);
		dateTV = (TextView) findViewById(R.id.dateTextView);
		dateTV.setText(new SimpleDateFormat("yyyy-MM-dd E").format(new Date()));
		timeTV.setText(new SimpleDateFormat("HH:mm").format(new Date()));

		// 设置皮肤
		if (ser.getSkin() != ConfValue.Skin_Pink) {
			turnBoyTheme(R.id.date, 4);
		}

		if (state && !repeat) { // 在浏览模式，且非复习模式下
			rows = ser.getTopRows(RowEnglish.tablename, StudyNum, false);
			mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

				@Override
				public void onPageSelected(int arg0) {
					if (arg0 > 0) {
						RowEnglish row = (RowEnglish) rows.get(arg0 - 1);
						scan(row.tablename, row.english, row.Remembered_Times);
					}
					if (arg0 == views.size() - 1) {
						StudyActivity.this.finish();
					}
				}

				@Override
				public void onPageScrolled(int arg0, float arg1, int arg2) {
				}

				@Override
				public void onPageScrollStateChanged(int arg0) {
				}
			});
			mViewPager.setAdapter(initPages());
			mViewPager.setOnTouchListener(new OnTouchListener() {
				private float old_y, old_x;

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					int item = mViewPager.getCurrentItem();
					View vintouch = views.get(item);
					mainTextView = (TextView) vintouch
							.findViewById(R.id.mainTextView);
					viceTextView = (TextView) vintouch
							.findViewById(R.id.viceTextView);
					gotittv = (TextView) vintouch.findViewById(R.id.gotittv);
					unlocktv = (TextView) vintouch
							.findViewById(R.id.unlockrightnowtv);
					System.out.println("touch");
					// TODO Auto-generated method stub

					switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						gotittv.setText("上滑标记单词为掌握");
						unlocktv.setText("下滑紧急解锁");
						if (ChEn) {
							mainTextView.setText(((RowEnglish) rows.get(item)).english);
						} else {
							viceTextView.setText(((RowEnglish) rows.get(item)).chinese);
						}
						old_y = event.getY();
						old_x = event.getX();
						break;
					case MotionEvent.ACTION_UP:
						gotittv.setText("");
						unlocktv.setText("");
						old_y = event.getY() - old_y;
						old_x = event.getX() - old_x;
						if (old_y > lingmindu && old_y > old_x)
							StudyActivity.this.finish();
						else if (old_y < -1 * lingmindu && old_y < old_x) {
							RowEnglish row = (RowEnglish) rows.get(item);
							gotIt(row.tablename, row.english);
							if (item == rows.size() - 1)
								StudyActivity.this.finish();
							else {
								rows.remove(item);
								mPagerAdapter.removeView(mViewPager, item);
							}
						}
						break;
					}

					mainvicetvLayout = (RelativeLayout) views.get(
							mViewPager.getCurrentItem()).findViewById(
							R.id.mainviceTextlay);

					switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						origin_x = mainvicetvLayout.getLeft();
						origin_y = mainvicetvLayout.getTop();
						spany = event.getY() - mainvicetvLayout.getTop();
						break;
					case MotionEvent.ACTION_MOVE:
						// 得到X，Y座标
						mainvicetvLayout.setTop((int) (event.getY() - spany));
						break;
					case MotionEvent.ACTION_UP:
						mainvicetvLayout.setLeft(origin_x);
						mainvicetvLayout.setTop(origin_y);
						break;
					}

					return false;
				}
			});
		} else {
			ques = ser.getQuestions(RowEnglish.tablename, StudyNum);
			mViewPager.setAdapter(initAnsPages());
			mViewPager.setOnTouchListener(new OnTouchListener() {
				private float old_y;

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					int item = mViewPager.getCurrentItem();
					// TODO Auto-generated method stub
					switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						old_y = event.getY();
						break;
					case MotionEvent.ACTION_UP:
						old_y = event.getY() - old_y;
						if (old_y > lingmindu)
							StudyActivity.this.finish();
						break;
					}
					return true;
				}
			});
		}
	}

	protected void gotIt(String tablename, String english) {
		// TODO Auto-generated method stub
		ser.updateDataRow_gotit(tablename, english);
		// mViewPager.setCurrentItem(currentPos);
		Log.v(tag, "learned " + english);
	}

	protected void scan(String tablename, String english, int remembered_Times) {
		// TODO Auto-generated method stub
		if (mViewPager.getCurrentItem() > max_visited_Item) {
			ser.updateDataRow_scan(tablename, english, remembered_Times);
			max_visited_Item = mViewPager.getCurrentItem();
		}
	}

	/**
	 * 选了某个选项，记录答题对错情况
	 * 
	 * @param which
	 *            选项序号
	 */
	private void buttonItemClick(int which) {
		// long startMs = System.currentTimeMillis();
		int item = mViewPager.getCurrentItem();
		ChoiceQuestion q = ques.get(item);
		// initBtnBkg(2, q);
		String english = ChEn ? q.items[q.ansPos] : q.mainText;
		if (q.ansPos == which) {
			gotIt(RowEnglish.tablename, english);
			rightAnsStr += q.mainText + "   " + q.items[q.ansPos] + "\r\n";
		} else {
			scan(RowEnglish.tablename, english, q.remembered_times);
			if (which != 3)
				testWrong(english);
			wrongAnsStr += q.mainText + "   " + q.items[q.ansPos] + "\r\n";
		}
		if (item == ques.size() - 1) {
			rightAns.setText(rightAnsStr);
			wrongAns.setText(wrongAnsStr);
		}
		ques.remove(item);
		mPagerAdapter.removeView(mViewPager, item);
	}

	private void testWrong(String english) {
		// TODO Auto-generated method stub
		ser.updateDataRow_testWrong(english);
	}

	public int currentPos;

	private float spany;
	private int origin_x, origin_y;

	class myPagerAdapter extends PagerAdapter {
		private ArrayList<View> views;
		private ArrayList<String> titles;

		public myPagerAdapter(ArrayList<View> views, ArrayList<String> titles) {
			this.views = views;
			this.titles = titles;
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == ((View) object);
		}

		@Override
		public int getCount() {
			return views.size();
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			// TODO Auto-generated method stub
			((ViewPager) container).removeView(views.get(position));
		}

		@Override
		public int getItemPosition(Object object) {
			// TODO Auto-generated method stub
			return POSITION_NONE;
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			// TODO Auto-generated method stub
			return super.instantiateItem(container, position);
		}

		@Override
		public CharSequence getPageTitle(int position) {
			return titles.get(position);
		}

		@Override
		public Object instantiateItem(View container, int position) {
			((ViewPager) container).addView(views.get(position));
			return views.get(position);
		}

		public int addView(View v, int position) {
			views.add(position, v);
			return position;
		}

		public int addView(View v) {
			return addView(v, views.size());
		}

		public int removeView(ViewPager pager, View v) {
			return removeView(pager, views.indexOf(v));
		}

		public int removeView(ViewPager pager, int position) {
			currentPos = position;
			Log.v("removeview",
					String.valueOf(100 * position + pager.getCurrentItem()));
			if (state && !repeat) {
				views.remove(position);
				pager.getAdapter().notifyDataSetChanged();
			} else {
				pager.setAdapter(null);
				views.remove(position);
				pager.setAdapter(this);
			}
			return position;
		}

		public View getView(int position) {
			return views.get(position);
		}
	}

	@Override
	public void init() {
		// TODO Auto-generated method stub
		state = ser.getModeNow();
		initViewPager();
		// 错题巩固模式下，不算解锁
		if (!repeat)
			ser.unlock();
	}

	@Override
	public void setTheme() {
		// TODO Auto-generated method stub

	}

}
